const http = require("http");
const url = require("url");
const fs = require("fs");
const querystring = require("querystring");
const uuid = require("node-uuid");
// const mysql = require("mysql");

// const connection = mysql.createConnection({ host : "180.76.170.96", user : 'root', password : '123456', port: '6033', database: 'youle' }); 




http.createServer((req,res)=>{
    if(req.url !== "/favicon.ico"){
        const urlObj = url.parse(req.url,true);
        switch(urlObj.pathname){
            case "/api":
                ajaxHandle(req,res);
                break;
            default:
                fileHandle(req,res);
        }
    }
}).listen("8080");

// localhost:8080/api?type=...

function ajaxHandle(req,res){
    let data = "";
    req.on("data",(s)=>{
        data += s;
    })
    req.on("end",()=>{
        if(data === ""){
            const urlObj = url.parse(req.url,true);
            data = urlObj.query;
    }else{
        data = querystring.parse(data);
    }
    switch(data.type){
        case "login":
            login(req,res,data);
            break;
        case "register":
            register(req,res,data);
            break;
        case "goods":
            goods(req,res,data);
            break;
        case "cart":
            goods(req,res,data);
            break;
        // case "goods":
        //     goodsMessages(req, res, data);
        //     break;   
        case "data":
            getIndexData(req, res,data);
            break; 
        // case "details":
        //     getDetail(req, res,data);
        //     break; 
        default:
            res.write("404");
            res.end();
        }
    })
}


//假设的数据库
    //state登录状态登录：1 未登录：0 默认：0
// [{user:"admin",pass:123,state:0},{}]
 
let userMsg = [];

function login(req,res,data){
    //登录
    //比对用户密码数据
    let i;
    const onoff = userMsg.some((val,idx)=>{
        i = idx;
        return val.user === data.user;
    })

    let msg = {};
    if(onoff){
        if(userMsg[i].pass === data.pass){
            userMsg[i].state = 1;    
            msg = {code:200,msg:"登录成功",data:userMsg[i]};
        }else{
            msg = {code:400,msg:"用户名密码不匹配",data:"NOT DATA"}
        }
    }else{
        msg = {code:404,msg:"用户名不存在，请您注册",data:"NOT DATA"}
    }
    //前后端交互一定要用交互json字符
    res.write(JSON.stringify(msg));
    //停止当前请求
    res.end();
}  

// function goodsMessages(req, res, data){
//     //连s接数据库
//     connection.connect();
//     const sql = "select * from goods";
//     connection.query(sql, function(err, result){
//         if(err){
//             console.log('[SERVER ERROR] - ', err.message);
//             return;
//         }
//         res.write(JSON.stringify(result));
//         res.end();
//     })
//     //关闭数据库连接
//     connection.end();
// }


function register(req,res,data){
    // 注册
    // 存用户密码数据
    let i;
    // 查看数据库中是否已经有重复数据
    const onoff = userMsg.some((val,idx)=>{
        i=idx;
        return val.user === data.user;
    });

    let msg = {};
    //如果有重复数据，注册失败
    if(onoff){
        msg = {code:1,msg:"用户名重复",data:"NOT DATA"};
    }else{
        const v1Str = uuid.v1()
        //没有重复，再进行注册
        userMsg.push({
            userId:v1Str,
            user:data.user,
            pass:data.pass,
            state:0
        })
        msg = {
                code:200,
                msg:"注册成功",
                data:{
                userId:v1Str,
                user:data.user,
                pass:data.pass,
                state:0
            }
        };
    }
    //前后端交互一定要用交互json字符
    res.write(JSON.stringify(msg));
    //停止当前请求
    res.end();
}

function goods(req,res,data){
    let goodsData = fs.readFileSync("./www/data/goods.json");
    res.write(goodsData);
    res.end();
}

function getIndexData(req, res, data){
    let indexData = fs.readFileSync("./www/data/data.json");
    res.write(indexData);
    res.end();
}

function getDetail(req, res, data){
    let detailData = fs.readFileSync("./www/data/goods.json");
    res.write(detailData);
    res.end();
}


function user(req,res,data){
    res.write("用户数据给你了");
    res.end();
}



function fileHandle(req,res){
    const urlObj = url.parse(req.url);
    const path = "./www" + urlObj.pathname;
    fs.readFile(path,(err,data)=>{
        if(err){
            res.write("404");
        }else{
            res.write(data);
        }
        res.end();
    })
}